#version 330

in vec3 ex_PosW;
in vec3 ex_NormalW;
in vec2 ex_TexCoord;

struct SpotLightInfo {
    vec4 position;   // Position in eye coords
    vec3 intensity;
    vec3 direction;  // Direction of the spotlight in eye coords.
    float exponent;  // Angular attenuation exponent
    float cutoff;    // Cutoff angle (between 0 and 90)
};
uniform SpotLightInfo Spot;

uniform vec3 kd;
uniform vec3 ka;
uniform vec3 ks;
uniform float shininess;

out vec4 finalColor;

vec3 adsWithSpotlight()
{
	vec3 s = normalize( vec3( Spot.position) - ex_PosW );
    vec3 spotDir = normalize( Spot.direction);
    float angle = acos( dot(-s, spotDir) );
    float cutoff = radians( clamp( Spot.cutoff, 0.0, 90.0 ) );
    vec3 ambient = Spot.intensity * ka;

    if( angle < cutoff ) {
        float spotFactor = pow( dot(-s, spotDir), Spot.exponent );
        vec3 v = normalize(vec3(-ex_PosW));
        vec3 h = normalize( v + s );

        return
            ambient +
            spotFactor * Spot.intensity * (
              kd * max( dot(s, ex_NormalW), 0.0 ) +
              ks * pow( max( dot(h, ex_NormalW), 0.0 ), shininess )
           );
    } else {
        return ambient;
    }
}

void main()
{
	finalColor = vec4(adsWithSpotlight(), 1.0);
}